package com.jasonm.rssminer.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.MappingSqlQuery;

import com.jasonm.rssminer.dto.UserDTO;

public class UserDAO {

	private class UserDaoInner extends MappingSqlQuery<UserDTO> {
		static final String query = "select id, first_name, last_name, password from user where email = ?";

		public UserDaoInner(DataSource ds) {
			super(ds, query);
			super.declareParameter(new SqlParameter("email", Types.VARCHAR));
			compile();
		}

		@Override
		protected UserDTO mapRow(ResultSet rs, int rowNumber)
				throws SQLException {
			UserDTO userDTO = new UserDTO();
			userDTO.setId((Integer) rs.getObject("id"));
			userDTO.setFirstName((String) rs.getObject("first_name"));
			userDTO.setLastName((String) rs.getObject("last_name"));
			userDTO.setPassword((String) rs.getObject("password"));
			return userDTO;
		}
	}

	private UserDaoInner query;

	public UserDAO(DataSource ds) {
		if (query == null) {
			query = new UserDaoInner(ds);
		}
	}

	public UserDTO getUser(String email) {
		return query.findObject(email);
	}
	
	public List<UserDTO> getUsers() {
		return query.execute();
	}

}
